package com.lovi.thread_;

import com.lovi.common.Message;
import com.lovi.common.MessageType;
import com.lovi.utils.ScannerUtils;
import lombok.Data;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

/**
 * 开启客户端和服务端连接通信的线程
 */
@Data
public class ClientConnectServerThread extends Thread {
    //线程同步，持有socket对象
    private Socket socket;

    public ClientConnectServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //客户端需要不断的读取服务端的信息
        while (true) {
            System.out.println("客户端线程，等待读取从服务器端发送的信息....");
            try {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message msg = (Message) ois.readObject();
                //普通聊天消息（私聊消息）
                if (MessageType.MESSAGE_COMM_MES.equals(msg.getMestype())) {
                    System.out.println("\n从服务器获取了消息：" + msg.getSender() + " 对 "
                            + msg.getGetter() + " 说：" + msg.getContent());
                }
                //群聊消息
                if (MessageType.MESSAGE_TO_ALL_MES.equals(msg.getMestype())){
                    System.out.println("\n群聊消息：用户" + msg.getSender() + " 对大家说：" + msg.getContent());
                }
                //返回在线用户列表
                if (MessageType.MESSAGE_RET_ONLINE_FRIEND.equals(msg.getMestype())) {
                    String content = msg.getContent();
                    String[] s = content.split(" ");
                    System.out.println("\n=====当前在线用户列表=====");
                    for (String value : s) {
                        System.out.println(value);
                    }
                }
                //退出系统
                if (MessageType.MESSAGE_CLIENT_EXIT.equals(msg.getMestype())) {
                    ManageClientConnectServerThread.removeClientConnect(msg.getGetter());
                    System.out.println("用户" + msg.getGetter() + "成功退出系统");
                    break;
                }
                //接收文件
                if (MessageType.MESSAGE_FILE_MES.equals(msg.getMestype())) {
                    System.out.println("用户" + msg.getSender() + "给你发送了一个文件，已经下载到本地"
                            + msg.getTargetFilePath());
                    FileOutputStream fos = new FileOutputStream(msg.getTargetFilePath());
                    fos.write(msg.getFileBytes());
                    fos.flush();
                    fos.close();
                }
            } catch (IOException e) {
                System.out.println("读取服务器消息异常:" + e.getMessage());
            } catch (ClassNotFoundException e) {
                System.out.println("ClassNotFound异常:" + e.getMessage());
            }
        }

    }
}
